import { useState } from 'react'
import { Button } from '@/components/ui/button'
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card'
import { getApiBaseUrl, buildApiUrl } from '@/lib/api'

export function ApiTest() {
  const [result, setResult] = useState<string>('')
  const [isLoading, setIsLoading] = useState(false)

  const testConnection = async () => {
    setIsLoading(true)
    setResult('')
    
    try {
      const baseUrl = getApiBaseUrl()
      const loginUrl = buildApiUrl('/huibanhao/login')
      
      setResult(`Base URL: ${baseUrl}\nLogin URL: ${loginUrl}\n\n正在测试连接...`)
      
      // 测试OPTIONS请求（预检请求）
      const response = await fetch(loginUrl, {
        method: 'OPTIONS',
        headers: {
          'Accept': 'application/json',
          'Content-Type': 'application/json',
        },
        credentials: 'include',
        mode: 'cors',
      })
      
      setResult(prev => prev + `\nOPTIONS请求状态: ${response.status}`)
      setResult(prev => prev + `\nOPTIONS请求响应头: ${JSON.stringify([...response.headers.entries()], null, 2)}`)
      
    } catch (error) {
      setResult(prev => prev + `\n错误: ${error instanceof Error ? error.message : String(error)}`)
    } finally {
      setIsLoading(false)
    }
  }

  const testLogin = async () => {
    setIsLoading(true)
    setResult('')
    
    try {
      const loginUrl = buildApiUrl('/huibanhao/login')
      
      setResult(`正在测试登录请求到: ${loginUrl}`)
      
      const response = await fetch(loginUrl, {
        method: 'POST',
        headers: {
          'Accept': 'application/json',
          'Content-Type': 'application/json',
        },
        credentials: 'include',
        mode: 'cors',
        body: JSON.stringify({
          phone: '17621010304',
          password: '123456'
        })
      })
      
      const data = await response.text()
      
      setResult(prev => prev + `\n状态码: ${response.status}`)
      setResult(prev => prev + `\n响应头: ${JSON.stringify([...response.headers.entries()], null, 2)}`)
      setResult(prev => prev + `\n响应内容: ${data}`)
      
    } catch (error) {
      setResult(prev => prev + `\n错误: ${error instanceof Error ? error.message : String(error)}`)
    } finally {
      setIsLoading(false)
    }
  }

  return (
    <Card className="w-full max-w-2xl mx-auto mt-8">
      <CardHeader>
        <CardTitle>API连接测试</CardTitle>
        <CardDescription>
          测试与后端API的连接状态
        </CardDescription>
      </CardHeader>
      <CardContent className="space-y-4">
        <div className="flex gap-2">
          <Button onClick={testConnection} disabled={isLoading}>
            {isLoading ? '测试中...' : '测试连接'}
          </Button>
          <Button onClick={testLogin} disabled={isLoading} variant="outline">
            {isLoading ? '登录中...' : '测试登录'}
          </Button>
        </div>
        
        {result && (
          <div className="mt-4">
            <h4 className="font-medium mb-2">测试结果:</h4>
            <pre className="bg-gray-100 dark:bg-gray-800 p-4 rounded-md text-sm overflow-auto max-h-96 whitespace-pre-wrap">
              {result}
            </pre>
          </div>
        )}
        
        <div className="mt-4 text-sm text-gray-600 dark:text-gray-400">
          <p><strong>当前配置:</strong></p>
          <p>Base URL: {getApiBaseUrl()}</p>
          <p>Login Endpoint: {buildApiUrl('/huibanhao/login')}</p>
          <p>环境: {import.meta.env.MODE}</p>
        </div>
      </CardContent>
    </Card>
  )
}
